import os

from flask import Flask
from flask import request, send_file
import decode_mars_nocrypt_log_file
from datetime import datetime
import urllib2
import file_util as fu

app = Flask(__name__)


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


@app.route('/decode_log_url', methods=['GET', 'POST'])
def decode_file_url():
    file_url = request.args['file_url']
    zip_flag = request.args['zip_flag']

    f = urllib2.urlopen(file_url)
    data = f.read()

    c_time = str(datetime.now())
    xlog_original = './static/' + c_time + '_url.xlog'
    xlog_decode = './static/' + c_time + '_url_decode.log'

    if zip_flag == '1':
        xlog_original = './static/' + c_time + '.zip'

    with open(xlog_original, 'wb') as code:
        code.write(data)

    if zip_flag == '1':
        # xlog_original = xlog_original.replace('.zip', '')
        xlog_original = fu.unzip(xlog_original)
        xlog_list = fu.find_xLog(os.getcwd() + xlog_original.replace("./", "/"))
        print 'log file size ' + str(xlog_list.__len__())
        if xlog_list.__len__() == 0:
            return 'no xlog file in zip ' + file_url
        elif xlog_list.__len__() == 1:
            xlog_original = xlog_list[0]
            xlog_decode = xlog_decode + '.log'
            return decode_by_xlog(xlog_original, xlog_decode)
        else:
            zip_list = []
            for original in xlog_list:
                original_decode = original + '.log'
                decode_by_xlog(original, original_decode)
                zip_list.append(original_decode)
            result_zip = str(xlog_original) + '/result.zip'
            fu.to_zip(zip_list, result_zip)
            return send_file(result_zip)
    return decode_by_xlog(xlog_original, xlog_decode)


@app.route('/decode_log', methods=['POST'])
def decode_file():
    if request.method == 'POST':
        f = request.files['log_file']
        c_time = str(datetime.now())
        xlog_original = './static/' + c_time + '.xlog'
        xlog_decode = './static/' + c_time + '_decode.log'
        f.save(xlog_original)
        return decode_by_xlog(xlog_original, xlog_decode)


def decode_by_xlog(original, decode):
    decode_mars_nocrypt_log_file.decode_file([original, decode])
    try:
        # return 'download file by path: ' + decode
        return send_file(decode)
    except Exception as e:
        return 'something wrong, download file by path: ' + decode


if __name__ == '__main__':
    app.run()
